﻿using Intex.Tools;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using System;
using System.Collections;
using System.Data;
using System.Linq;
namespace WPFExcelReport
{
    public partial class YCAAUTOEKData
    {
        public string TraceMessage = "";
        public string ApplicationPath
        {
            get { return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); }
        }
        /// <summary>
        /// GetJob is used to collect the tasks to finish the order creation
        /// </summary>
        /// <param name="FInterID"></param>
        /// <returns></returns>
        public DataSet GetJob(ref  bool last)
        {

            ArrayList tbs = new ArrayList() { "A", "B", "C" };
            string a = (string)tbs[0];
            DataSet SResult = new DataSet();
            DataSet SReturn = new DataSet();

            try
            {
                string fileDone;
                string filestemp = @"C:\IntexReport\Data\YCAATEK\01Temp";
                string[] files = System.IO.Directory.GetFiles(filestemp);
                foreach (string file in files)
                {
                    fileDone = file.Replace(@"\01Temp\", @"\02Incoming\");
                    System.IO.File.Move(file, fileDone);
                }
                string files2p = @"C:\IntexReport\Data\YCAATEK\02Incoming";
                files = System.IO.Directory.GetFiles(files2p);

                if (files.Length > 0)
                {
                    string file = files[0];
                    SResult.ReadXml(file);
                    SReturn.Merge(SResult);
                    SResult = ConsolidateData(SReturn, file);
                    SReturn.Merge(SResult);                    
                    fileDone = file.Replace(@"\02Incoming\", @"\03Done\");
                    System.IO.File.Move(file, fileDone);
                }
                if (files.Length == 1)
                    last = true;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {

            }
            return SReturn;
        } 
        private DataSet CreateEKKOPF_EXT(DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            try
            {
                /*                
                 * JANE    	EKKNEUB
                 * 20081126	EKKNEUD
                 * B	EKKAUFGRP
                 * BE	EKKAUFART
                 * 8	EKKARTGR
                 * 5464000	EKKWE1*/
                DataTable ekk = new DataTable();
                ekk.Columns.Add("EKKAUFKRS", typeof(string));
                ekk.Columns.Add("EKKAUFLFD", typeof(string));
                ekk.Columns.Add("EKKNEUB", typeof(string));
                ekk.Columns.Add("EKKNEUD", typeof(string));
                ekk.Columns.Add("EKKAUFGRP", typeof(string));
                ekk.Columns.Add("EKKAUFART", typeof(string));
                ekk.Columns.Add("EKKARTGR", typeof(string));
                ekk.Columns.Add("EKKBUCHKRS", typeof(string));
                ekk.Columns.Add("EKKLIEFNR", typeof(string));
                ekk.Columns.Add("EKKME1", typeof(double));
                ekk.Columns.Add("EKKWE1", typeof(double));
                //INTEXDB.EKKOPF.Clone();
                //src.Tables["EKPOS_EXT"].Columns["EKPWE1"].DataType = typeof(double);
                var query = from EKP in src.Tables["EKPOS_EXT"].AsEnumerable()
                            group EKP by new
                            {
                                KRS = EKP["EKPAUFKRS"],
                                LFD = EKP["EKPAUFLFD"],
                            }
                                into g
                                select new
                                {
                                    EKP = g.Key,
                                    EKKNEUB = g.Max(EKP => EKP.Field<string>("EKPNEUB")),
                                    EKKNEUD = g.Max(EKP => EKP.Field<string>("EKPNEUD")),
                                    EKKAUFGRP = g.Max(EKP => EKP.Field<string>("EKPAUFGRP")),
                                    EKKAUFART = g.Max(EKP => EKP.Field<string>("EKPAUFART")),
                                    EKKARTGR = g.Max(EKP => EKP.Field<string>("EKPARTGR")),
                                    EKKLIEFNR = g.Max(EKP => EKP.Field<string>("EKPLIEFNR")),
                                    EKKBUCHKRS = g.Max(EKP => EKP.Field<string>("EKKBUCHKRS")),
                                    EKKME1 = g.Sum(EKP => Convert.ToDouble(EKP.Field<string>("EKPME1"))),
                                    EKKWE1 = g.Sum(EKP => Convert.ToDouble(EKP.Field<string>("EKPWE1"))),
                                };

                foreach (var ekp in query)
                {
                    DataRow rowTemp = ekk.NewRow();
                    rowTemp["EKKAUFKRS"] = ekp.EKP.KRS;
                    rowTemp["EKKAUFLFD"] = ekp.EKP.LFD;
                    rowTemp["EKKNEUB"] = ekp.EKKNEUB;
                    rowTemp["EKKNEUD"] = ekp.EKKNEUD;
                    rowTemp["EKKAUFGRP"] = ekp.EKKAUFGRP;
                    rowTemp["EKKAUFART"] = ekp.EKKAUFART;
                    rowTemp["EKKARTGR"] = ekp.EKKARTGR;
                    rowTemp["EKKLIEFNR"] = ekp.EKKLIEFNR;
                    rowTemp["EKKBUCHKRS"] = ekp.EKKBUCHKRS;
                    //rowTemp["EKKWE1"]=0;
                    rowTemp["EKKME1"] = ekp.EKKME1;
                    rowTemp["EKKWE1"] = ekp.EKKWE1;
                    ekk.Rows.Add(rowTemp);
                }
                ekk.TableName = "EKKOPF_EXT";
                setReturn.Merge(ekk);
                TraceMessage+=ekk.Rows[0]["EKKAUFKRS"].ToString()+ekk.Rows[0]["EKKAUFKRS"].ToString()+"创建"+Environment.NewLine;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                TraceMessage+=ex.StackTrace+Environment.NewLine+ex.Message.ToString();
            }
            return setReturn;
        }
      
        private DataSet ConsolidateData(DataSet src, string file)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            bool IsCreateEKKOPF_EXT = true;
            try
            {
                //获取ABPOS_EXT的VA10
                //查找对应的GS07
                //更新ABPOS_EXT
                //更新EXCEL
                if (IsCreateEKKOPF_EXT)
                {
                    setResult = CreateEKKOPF_EXT(src, file);
                    setReturn.Merge(setResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        public DataSet LoadExcelVKVV()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            try
            {
                #region=======MAPINTEX================
                string fileroot = @"C:\IntexReport\Data\YCAATEK\EXCEL";
                string[] files = System.IO.Directory.GetFiles(fileroot);
                foreach (string file in files)
                {
                    string ShortName = file.Substring(file.LastIndexOf("\\") + 1);                    
                    if (!ShortName.StartsWith("EK"))
                        continue;
                    EventDispatcher.Instance.RaiseStatus("装载:" + ShortName + "开始", StatusEventType.StopProgress);
                    if (exAgent == null)
                    {
                        exAgent = new ExcelX.ExcelLib.ExcelAgent(file);
                    }
                    if (System.IO.File.Exists(file))
                    {
                        setResult = new DataSet();
                        setResult = exAgent.LoadDataTableDef(file, "", 50);
                        if (setResult.Tables.Contains("EKPOS_EXT"))
                        {
                            setResult.Tables["EKPOS_EXT"].Clear();
                        }
                        setReturn.Merge(setResult); 
                        string xml = @"C:\IntexReport\Data\YCAATEK\01Temp\" + ShortName.Replace(".xls", "_" + DateTime.Now.ToFileTime().ToString() + ".XML");
                        if (System.IO.File.Exists(xml))
                        {
                            System.IO.File.Delete(xml);
                        }
                        if (setResult != null)
                        {
                            setResult.WriteXml(xml);
                        }
                        System.IO.File.Copy(file, fileroot + "\\P_" + ShortName);
                        exAgent.Close();
                        System.IO.File.Delete(file);
                        EventDispatcher.Instance.RaiseStatus("装载:" + ShortName + "完成", StatusEventType.StopProgress);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (exAgent != null)
                {
                    exAgent.KillExcelProcess();
                    exAgent.Dispose();
                    GC.Collect();
                    exAgent.Close();
                    exAgent = null;
                }
            }
            return setReturn;
        }

    }
}
